package com.busi.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public abstract class DHCoder {

	// 非对称加密密钥算法
	private static final String KEY_ALGORITHM = "DH";
	// 本地密钥算法，即对称加密密钥算法 可选DES、DESede和AES算法
	private static final String SECRET_ALGORITHM = "AES";
	// 密钥长度 DH算法默认密钥长度为1024 密钥长度必须是64的倍数，其范围在512位到1024位之间。
	private static final int KEY_SIZE = 512;
	// 公钥
	private static final String PUBLIC_KEY = "DHPublicKey";
	// 私钥
	private static final String PRIVATE_KEY = "DHPrivateKey";

	/**
	 * 初始化甲方密钥
	 * 
	 * @return
	 */
	public static Map<String, Object> initKey() {
		try {
			// 实例化密钥对生成器
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
			// 初始化密钥对生成器
			keyPairGenerator.initialize(KEY_SIZE);
			// 生成密钥对
			KeyPair keyPair = keyPairGenerator.generateKeyPair();
			// 甲方公钥
			DHPublicKey dhPublicKey = (DHPublicKey) keyPair.getPublic();
			// 甲方私钥
			DHPrivateKey dhPrivateKey = (DHPrivateKey) keyPair.getPrivate();
			// 将密钥对存入Map中
			Map<String, Object> keyMap = new HashMap<String, Object>(2);
			keyMap.put(PUBLIC_KEY, dhPublicKey);
			keyMap.put(PRIVATE_KEY, dhPrivateKey);
			return keyMap;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 初始化乙方密钥
	 * 
	 * @param key 甲方公钥
	 * @return
	 */
	public static Map<String, Object> initKey(byte[] key) {
		try {
			// 解析甲方公钥 转换公钥材料
			X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(key);
			// 实例化密钥工厂
			KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
			// 产生公钥
			PublicKey publicKey = factory.generatePublic(encodedKeySpec);
			// 由甲方公钥构建乙方密钥
			DHParameterSpec dhParameterSpec = ((DHPublicKey) publicKey).getParams();
			// 实例化密钥对生成器
			KeyPairGenerator generator = KeyPairGenerator.getInstance(factory.getAlgorithm());
			// 初始化密钥对生成器
			generator.initialize(dhParameterSpec);
			// 产生密钥对
			KeyPair keyPair = generator.genKeyPair();
			// 乙方公钥
			DHPublicKey dhPublicKey = (DHPublicKey) keyPair.getPublic();
			// 乙方私钥
			DHPrivateKey dhPrivateKey = (DHPrivateKey) keyPair.getPrivate();
			// 将密钥对存储在Map中
			Map<String, Object> keyMap = new HashMap<String, Object>(2);
			keyMap.put(PUBLIC_KEY, dhPublicKey);
			keyMap.put(PRIVATE_KEY, dhPrivateKey);
			return keyMap;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 加密
	 * 
	 * @param data 待加密数据
	 * @param key  密钥
	 * @return
	 */
	public static File encryptFile(File srcFileName, File destFileName, byte[] key) {
		OutputStream outputWriter = null;
		FileInputStream inputReader = null;
		try {
			inputReader = new FileInputStream(srcFileName);
			outputWriter = new FileOutputStream(destFileName);
			// 生成本地密钥
			SecretKey secretKey = new SecretKeySpec(key, SECRET_ALGORITHM);
			// 数据加密
			Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			// 以加密流写入文件
			CipherInputStream cipherInputStream = new CipherInputStream(inputReader, cipher);
			byte[] cache = new byte[1024];
			int nRead = 0;
			while ((nRead = cipherInputStream.read(cache)) != -1) {
				outputWriter.write(cache, 0, nRead);
				outputWriter.flush();
			}
			cipherInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				inputReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				outputWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return destFileName;
	}

	/**
	 * 解密
	 * 
	 * @param data 待解密数据
	 * @param key  密钥
	 * @return
	 */
	public static File decryptFile(File sourceFile, File decryptFile, byte[] key) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		// 生成本地密钥
		SecretKey secretKey = new SecretKeySpec(key, SECRET_ALGORITHM);
		// 数据解密
		Cipher cipher;
		try {
			inputStream = new FileInputStream(sourceFile);
			outputStream = new FileOutputStream(decryptFile);
			cipher = Cipher.getInstance(secretKey.getAlgorithm());
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
			byte[] buffer = new byte[1024];
			int r;
			while ((r = inputStream.read(buffer)) >= 0) {
				cipherOutputStream.write(buffer, 0, r);
			}
			cipherOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return decryptFile;
	}

	/**
	 * 构建密钥
	 * 
	 * @param publicKey  公钥
	 * @param privateKey 密钥
	 * @return byte[] 本地密钥
	 */
	public static byte[] getSecretKey(byte[] publicKey, byte[] privateKey) {
		try {
			// 实例化密钥工厂
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			// 初始化公钥 密钥材料转换
			X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(publicKey);
			// 产生公钥
			PublicKey pubKey = keyFactory.generatePublic(encodedKeySpec);
			// 初始化私钥 密钥材料转换
			PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey);
			// 产生私钥
			PrivateKey priKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
			// 实例化
			KeyAgreement agreement = KeyAgreement.getInstance(keyFactory.getAlgorithm());
			// 初始化
			agreement.init(priKey);
			agreement.doPhase(pubKey, true);
			// 生成本地密钥
			SecretKey secretKey = agreement.generateSecret(SECRET_ALGORITHM);
			return secretKey.getEncoded();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 取得私钥
	 * 
	 * @param keyMap 密钥map
	 * @return
	 */
	public static byte[] getPrivateKey(Map<String, Object> keyMap) {
		Key key = (Key) keyMap.get(PRIVATE_KEY);
		return key.getEncoded();
	}

	/**
	 * 取得公钥
	 * 
	 * @param keyMap 密钥map
	 * @return
	 */
	public static byte[] getPublicKey(Map<String, Object> keyMap) {
		Key key = (Key) keyMap.get(PUBLIC_KEY);
		return key.getEncoded();
	}
}
